import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Hash, Clock, Trophy, Star, CheckCircle, XCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface DigitMemoryTestProps {
  onComplete: (result: TestResult) => void;
}

interface Trial {
  id: number;
  digit: number;
  isMatch: boolean; // 是否与N步前的数字相同
  nLevel: number; // N-back级别
}

export function DigitMemoryTest({ onComplete }: DigitMemoryTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentLevel, setCurrentLevel] = useState(1); // 从1-back开始
  const [currentTrial, setCurrentTrial] = useState(0);
  const [trials, setTrials] = useState<Trial[]>([]);
  const [responses, setResponses] = useState<boolean[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(480); // 8分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [trialStartTime, setTrialStartTime] = useState<number>(0);
  const [currentDigit, setCurrentDigit] = useState<number | null>(null);
  const [showDigit, setShowDigit] = useState(false);
  const [score, setScore] = useState(0);
  const [levelScores, setLevelScores] = useState<number[]>([]);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);

  const TRIALS_PER_LEVEL = 20;
  const MAX_LEVEL = 5;
  const DIGIT_DISPLAY_TIME = 500; // 数字显示时间
  const INTER_STIMULUS_INTERVAL = 2500; // 刺激间隔

  const generateTrials = (nLevel: number): Trial[] => {
    const newTrials: Trial[] = [];
    const digits = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    // 生成数字序列
    const sequence: number[] = [];
    for (let i = 0; i < TRIALS_PER_LEVEL; i++) {
      sequence.push(digits[Math.floor(Math.random() * digits.length)]);
    }
    
    // 确保有适当比例的匹配试次 (约30%)
    const matchCount = Math.floor(TRIALS_PER_LEVEL * 0.3);
    const matchPositions = new Set<number>();
    
    // 随机选择匹配位置 (必须在第N个试次之后)
    while (matchPositions.size < matchCount) {
      const pos = Math.floor(Math.random() * (TRIALS_PER_LEVEL - nLevel)) + nLevel;
      matchPositions.add(pos);
    }
    
    // 设置匹配试次
    matchPositions.forEach(pos => {
      sequence[pos] = sequence[pos - nLevel];
    });
    
    // 创建试次对象
    for (let i = 0; i < TRIALS_PER_LEVEL; i++) {
      const isMatch = i >= nLevel && sequence[i] === sequence[i - nLevel];
      newTrials.push({
        id: i,
        digit: sequence[i],
        isMatch,
        nLevel
      });
    }
    
    return newTrials;
  };

  useEffect(() => {
    if (stage === 'test') {
      const newTrials = generateTrials(currentLevel);
      setTrials(newTrials);
      setCurrentTrial(0);
      startTrial();
    }
  }, [stage, currentLevel]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const startTrial = () => {
    const trial = trials[currentTrial];
    if (!trial) return;

    setCurrentDigit(trial.digit);
    setShowDigit(true);
    setTrialStartTime(Date.now());

    // 显示数字
    setTimeout(() => {
      setShowDigit(false);
    }, DIGIT_DISPLAY_TIME);
  };

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleResponse = (userResponse: boolean) => {
    const trial = trials[currentTrial];
    const reactionTime = Date.now() - trialStartTime;
    const correct = userResponse === trial.isMatch;
    
    setResponses(prev => [...prev, userResponse]);
    setReactionTimes(prev => [...prev, reactionTime]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }
    
    // 显示反馈
    setFeedbackCorrect(correct);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      
      if (currentTrial < trials.length - 1) {
        setCurrentTrial(prev => prev + 1);
        setTimeout(() => {
          startTrial();
        }, 500);
      } else {
        // 当前级别完成
        finishLevel();
      }
    }, 800);
  };

  const finishLevel = () => {
    const levelTrials = trials.slice(0, currentTrial + 1);
    const levelResponses = responses.slice(-levelTrials.length);
    const levelCorrect = levelResponses.filter((response, index) => 
      response === levelTrials[index].isMatch
    ).length;
    const levelAccuracy = levelCorrect / levelTrials.length;
    
    setLevelScores(prev => [...prev, levelAccuracy]);
    
    // 判断是否继续下一级别
    if (levelAccuracy >= 0.75 && currentLevel < MAX_LEVEL) {
      // 准确率75%以上，进入下一级别
      setCurrentLevel(prev => prev + 1);
      setCurrentTrial(0);
      setResponses([]);
      setReactionTimes([]);
    } else {
      // 结束测试
      setStage('results');
    }
  };

  const handleComplete = () => {
    const totalTrials = responses.length;
    const totalCorrect = responses.filter((response, index) => {
      // 找到对应的试次
      let trialIndex = 0;
      for (let level = 1; level <= currentLevel; level++) {
        const levelTrialsCount = level === currentLevel ? currentTrial + 1 : TRIALS_PER_LEVEL;
        if (index < trialIndex + levelTrialsCount) {
          const levelTrials = generateTrials(level);
          const relativeIndex = index - trialIndex;
          return response === levelTrials[relativeIndex]?.isMatch;
        }
        trialIndex += levelTrialsCount;
      }
      return false;
    }).length;
    
    const overallAccuracy = Math.round((totalCorrect / totalTrials) * 100);
    const maxLevel = currentLevel;
    const workingMemorySpan = levelScores.length > 0 ? 
      levelScores.findIndex(score => score < 0.75) + 1 || levelScores.length : 1;
    
    // 计算最终得分
    const finalScore = Math.min(100, 
      Math.round(overallAccuracy + (workingMemorySpan - 1) * 10)
    );

    const averageReactionTime = Math.round(
      reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length
    );

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 计算各级别表现
    const levelPerformance = levelScores.map((accuracy, index) => ({
      level: index + 1,
      accuracy: Math.round(accuracy * 100),
      trials: TRIALS_PER_LEVEL
    }));

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'digit-memory',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTrials,
        totalCorrect,
        overallAccuracy,
        maxLevelReached: maxLevel,
        workingMemorySpan,
        averageReactionTime,
        levelPerformance,
        nBackCapacity: workingMemorySpan,
        totalScore: score
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-blue-700 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Hash className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">数字工作记忆测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您对数字序列的记忆和处理能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-6 border border-blue-100">
              <h3 className="font-semibold text-blue-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>您将看到一系列数字（1-9）依次出现</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>需要判断当前数字是否与N步前的数字相同</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>从1-back开始，准确率75%以上进入下一级别</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>数字显示0.5秒，然后选择"匹配"或"不匹配"</p>
                </div>
              </div>
            </div>

            {/* 示例说明 */}
            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200">
              <h4 className="font-semibold text-slate-700 mb-3 text-center">N-back示例</h4>
              <div className="space-y-3">
                <div className="text-center">
                  <div className="text-sm text-slate-600 mb-2">1-back示例：比较当前数字与前1个数字</div>
                  <div className="flex justify-center gap-2 mb-2">
                    <span className="w-8 h-8 bg-blue-100 rounded flex items-center justify-center">5</span>
                    <span className="w-8 h-8 bg-green-100 rounded flex items-center justify-center">3</span>
                    <span className="w-8 h-8 bg-red-100 rounded flex items-center justify-center font-bold">3</span>
                  </div>
                  <div className="text-xs text-green-600">匹配！（当前3 = 前1个3）</div>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-blue-700 mb-1">5</div>
                <div className="text-sm text-blue-700">最高级别</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-700 mb-1">20</div>
                <div className="text-sm text-indigo-700">试次/级别</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">8</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-blue-700 to-indigo-600 hover:from-blue-800 hover:to-indigo-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = ((currentLevel - 1) * TRIALS_PER_LEVEL + currentTrial) / (MAX_LEVEL * TRIALS_PER_LEVEL) * 100;
    const trial = trials[currentTrial];

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-blue-100 text-blue-700 border-blue-300">
              {currentLevel}-back
            </Badge>
            <Badge variant="outline" className="bg-indigo-100 text-indigo-700 border-indigo-300">
              试次 {currentTrial + 1} / {TRIALS_PER_LEVEL}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score} / {responses.length}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 指导信息 */}
        <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
          <CardContent className="py-4">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-blue-800">
                当前数字是否与前 {currentLevel} 个数字相同？
              </h3>
              {currentTrial < currentLevel && (
                <p className="text-sm text-blue-600 mt-1">
                  前 {currentLevel} 个试次无需判断，请记住数字
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
          <CardContent className="py-16">
            <div className="text-center space-y-8">
              <AnimatePresence mode="wait">
                {showDigit && currentDigit !== null && (
                  <motion.div
                    key={currentDigit}
                    initial={{ scale: 0.8, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 1.2, opacity: 0 }}
                    transition={{ duration: 0.3 }}
                    className="w-32 h-32 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto shadow-lg"
                  >
                    <span className="text-6xl font-bold text-white">
                      {currentDigit}
                    </span>
                  </motion.div>
                )}
              </AnimatePresence>

              {!showDigit && trial && currentTrial >= currentLevel && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="space-y-6"
                >
                  <div className="text-xl text-slate-700 mb-6">
                    刚才的数字 {trial.digit} 是否与前 {currentLevel} 个数字相同？
                  </div>
                  
                  <div className="flex justify-center gap-6">
                    <Button
                      onClick={() => handleResponse(true)}
                      className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-12 py-4 text-lg font-semibold shadow-lg"
                      size="lg"
                    >
                      <CheckCircle className="w-6 h-6 mr-2" />
                      匹配
                    </Button>
                    <Button
                      onClick={() => handleResponse(false)}
                      className="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-12 py-4 text-lg font-semibold shadow-lg"
                      size="lg"
                    >
                      <XCircle className="w-6 h-6 mr-2" />
                      不匹配
                    </Button>
                  </div>
                </motion.div>
              )}

              {!showDigit && trial && currentTrial < currentLevel && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="text-lg text-slate-600"
                >
                  请记住这个数字，下一个数字即将出现...
                </motion.div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 反馈弹窗 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50"
            >
              <Card className={`border-0 shadow-lg ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-3 px-6">
                  <div className="flex items-center gap-3">
                    {feedbackCorrect ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      <XCircle className="w-5 h-5" />
                    )}
                    <span className="font-semibold">
                      {feedbackCorrect ? '正确！' : '错误！'}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalTrials = responses.length;
    const totalCorrect = responses.filter((response, index) => {
      let trialIndex = 0;
      for (let level = 1; level <= currentLevel; level++) {
        const levelTrialsCount = level === currentLevel ? currentTrial + 1 : TRIALS_PER_LEVEL;
        if (index < trialIndex + levelTrialsCount) {
          const levelTrials = generateTrials(level);
          const relativeIndex = index - trialIndex;
          return response === levelTrials[relativeIndex]?.isMatch;
        }
        trialIndex += levelTrialsCount;
      }
      return false;
    }).length;
    
    const overallAccuracy = Math.round((totalCorrect / totalTrials) * 100);
    const workingMemorySpan = levelScores.length > 0 ? 
      levelScores.findIndex(score => score < 0.75) + 1 || levelScores.length : 1;
    
    const finalScore = Math.min(100, 
      Math.round(overallAccuracy + (workingMemorySpan - 1) * 10)
    );

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-blue-700 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-blue-700 to-indigo-600 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">数字工作记忆得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-blue-700 mb-1">{workingMemorySpan}</div>
                <div className="text-sm text-blue-700">记忆跨度</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-700 mb-1">{overallAccuracy}%</div>
                <div className="text-sm text-indigo-700">总准确率</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">最高级别</span>
                <span className="font-semibold text-slate-800">{currentLevel}-back</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">正确试次</span>
                <span className="font-semibold text-slate-800">{totalCorrect}/{totalTrials}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">N-back能力</span>
                <span className="font-semibold text-slate-800">{workingMemorySpan}</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-blue-700 to-indigo-600 hover:from-blue-800 hover:to-indigo-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}